package netty.study.first;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * @author songZiHao
 * @version 1.0.0
 * @ClassName TestHttpServerHandler.java
 * @Description TODO
 * @createTime 2020年04月10日 15:02:00
 *
 *
 * 方法执行顺序
 *  | handlerAdded       添加channelHandler,客户端与服务端连接建立的时候
 *  |—————channelRegistered  注册channelHandler
 *  |———————channelActive       激活channelHandler
 *  |_________channelRead0        进行channelHandler的回调
 *  |___________channelInactive      准备注销前的channelHandler
 *  |—————————————channelUnregistered   注销channelHandler
 */
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

	//客户端有请求的时候调用，处理客户端的请求并返回相应
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
		System.out.println(msg.getClass());

		System.out.println(ctx.channel().remoteAddress());
		if (msg instanceof  HttpRequest){
			HttpRequest request = (HttpRequest) msg;
			System.out.println("请求方法名："+request.getMethod());
			URI uri = new URI(request.getUri());
			if ("/favicon.ico".endsWith(uri.getPath())){
				System.out.println("请求favicon.ico");
				return;
			}
			ByteBuf content= Unpooled.copiedBuffer("Hello world", CharsetUtil.UTF_8);
			FullHttpResponse response=new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,content);
			response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
			response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());
			ctx.writeAndFlush(response);
		}
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("channel Active");
		super.channelActive(ctx);
	}

	@Override
	public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
		System.out.println("channel Registered");
		super.channelRegistered(ctx);
	}

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		System.out.println("handler Added");

		super.handlerAdded(ctx);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("channel Inactive");

		super.channelInactive(ctx);
	}

	@Override
	public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
		System.out.println("channel Unregistered");
		super.channelUnregistered(ctx);
	}
}
